<template>
	<view>
		<view class="login-btn" v-if="flag">
			<button style="margin: 40rpx 10rpx;" type="primary" @click="login" v-if="show" :disabled="loginFlag">
				<u-loadmore 
				        :status="status" 
				        loading-text="授权登录中..." 
				        loadmore-text="微信授权登录" 
				        nomore-text=""
						color="#fff"
						:fontSize="17"
						:iconSize="20"
				></u-loadmore>
			</button>
			<view v-else>
				<text style="display: block;margin: 40rpx 10rpx;color: rgb(164, 164, 164);">您还没有注册,请先注册哦</text>
				<button :disabled="loginFlag" open-type="getPhoneNumber" type="primary"
					       @getphonenumber="onGetPhoneNumber" >
						   <u-loadmore
						           :status="status" 
						           loading-text="授权注册登录中..." 
						           loadmore-text="手机号一键注册登录" 
						           nomore-text=""
								   color="#fff"
								   :fontSize="17"
								   :iconSize="20"
						   ></u-loadmore>
				</button>
			</view>
		</view>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {doLogin} from '@/utils/api.js'
	export default {
		data() {
			return {
				flag: false,
				show: true,
				loginFlag: false,
				status: 'loadmore',
				loginUserInfo: {},
				userInfo: null,
			}
		},
		onLoad(){
			// #ifdef H5
				console.log("H5端运行...")
				uni.switchTab({
					url:'/pages/index/index'
				})
			// #endif
			/* const userInfo = uni.getStorageSync("userInfo")
			if(userInfo != null && userInfo != ''){
				getApp().globalData.userInfo = JSON.parse(userInfo)
			} */
			
		},
		onReady() {
			if(getApp().globalData.userInfo != null && getApp().globalData.userInfo != ''){
				uni.$u.route({
					url: '/pages/index/index',
					type: 'switchTab'
				})
			}
			this.flag = true
		},
		methods: {
			onGetPhoneNumber(e){
				const that = this
				//解密手机号
				var msg = e.detail.errMsg
				var encryptedData = e.detail.encryptedData
				var iv = e.detail.iv
				that.status = 'loading'
				that.loginUserInfo.iv = iv
				that.loginUserInfo.encryptedData = encryptedData

				uni.showLoading({
					title: '正在注册登录中...'
				})
				//未注册, 获取手机号注册登录
				doLogin(that.loginUserInfo).then(res => {
					setTimeout(() => {
						that.loginSuccess(res)
					}, 200)
				}).catch(err => {
					getApp().globalData.toast[1].message = '请求出现了错误,授权注册登录失败'
					this.$refs.uToast.show({
						...getApp().globalData.toast[1],
						complete() {
							that.loginFlag = false
							that.status = 'loadmore'
						}
					})
					
				})
			},
			login(){
				const that = this;
				that.loginFlag = true
				that.status = 'loading'
				//步骤一: 弹出授权窗口
				uni.getUserProfile({
					desc:'用于获取您的个人信息',
					success(res) {
						//用户点击了允许, 拿到了用户信息
						let userInfo = res.userInfo;
						console.log("用户信息: " , userInfo)
						
						//步骤二: 调用uni.log(), 获取code
						uni.login({
							provider: 'weixin',	//指定登录服务提供商
							success(loginRes) {
								uni.showLoading({title: '登录中...'})
								//获取code
								const code = loginRes.code
								console.log("获取code成功: ", code)
								//步骤三: 向后端发送服务器请求, 带上参数: code 和 用户信息
								that.loginUserInfo = {code: code, nickName: userInfo.nickName, avatarUrl:userInfo.avatarUrl};
								doLogin(that.loginUserInfo).then(res => {
									that.loginUserInfo.sessionKey = res.sessionKey
									that.loginUserInfo.openid = res.openid
									if(res.tokenValue != null){	//已注册过, 登录成功
										that.loginSuccess(res)
										return
									}
									uni.hideLoading()
									that.loginFlag = false
									that.status = 'loadmore'
									that.show = false
								}).catch(err => {
									uni.hideLoading()
									getApp().globalData.toast[1].message = '请求出现了个错误,授权登录失败'
									that.$refs.uToast.show({
										...getApp().globalData.toast[1],
										complete() {
											that.loginFlag = false
											that.status = 'loadmore'
										}
									})
								})
								
							},
							fail(err){
								console.log(err)
							}
						})
					},
					fail(err) {
						console.log(err)
					}
				})
				
			},
			loginSuccess(res){
				const that = this
				getApp().globalData.phoneNumber = res.phoneNumber
				let saveInfo = {
					id: res.userId,
					phoneNumber:res.phoneNumber,
					nickname:that.loginUserInfo.nickName,
					avatar:that.loginUserInfo.avatarUrl,
					college: res.college,
				}
				uni.setStorage({
					key: 'userInfo',
					data: JSON.stringify(saveInfo)
				})
				getApp().globalData.userInfo = saveInfo
				uni.setStorage({
					key: 'loginToken',
					data: `${res.tokenHeader} ${res.tokenValue}`
				})
				uni.setStorage({
					key: 'imToken',
					data: res.imTokenValue
				})
				uni.hideLoading()
				getApp().globalData.toast[0].message = '登录成功'
				that.$refs.uToast.show({
					...getApp().globalData.toast[0],
					complete() {
						//index是tab页面, 只能这种方式跳转
						uni.switchTab({
							url:'/pages/index/index'
						})
					}
				})
			},
		
		}
	}
</script>

<style lang="scss" scoped>
	.login-btn {
		width: 90%;
		position: fixed;
		top: 400rpx;
		left: 40rpx;
		text-align: center;
	}
</style>
